package yc.star.common.security.service;

import cn.hutool.core.lang.UUID;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yc.star.common.constants.CacheConstant;
import yc.star.common.constants.JwtConstant;
import yc.star.common.redis.service.RedisService;
import yc.star.common.domain.LoginUser;
import yc.star.common.utils.JwtUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

// 操作用户登录的token方法
@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;

    // 登录时生成JWT返回给客户端，并将敏感信息存储到redis中
    public String createToken (Long userId,String secret,Integer identity,String nikeName,String headImage) {
        // 生成jwt的token
        Map<String, Object> claims = new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstant.LOGIN_USER_ID,userId);
        claims.put(JwtConstant.LOGIN_USER_KEY,userKey);
        String token = JwtUtils.createToken(claims, secret);

        // 生成唯一key
        String key = CacheConstant.LOGIN_TOKEN_KEY + userKey;
        // 设置value
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nikeName);
        loginUser.setHeadImage(headImage);
        // 存储到redis中
        redisService.setCacheObject(key,loginUser,CacheConstant.EXP, TimeUnit.MINUTES);
        return token;
    }

    // 在身份验证之后调用来延长token的时长
    public void extendToken (String token,String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return;
        }
        String tokenKey = CacheConstant.LOGIN_TOKEN_KEY + userKey;

        // 当有效时间剩余3个小时的时候进行延长redis中的token时长
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < CacheConstant.REFRESH_TIME) {
            // 重新延长token的有效时长为720分钟
            redisService.expire(tokenKey,CacheConstant.EXP,TimeUnit.MINUTES);
        }

    }

    // 解析token得到userKey
    public String getUserKey (String token,String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token:{},出现异常",token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token:{},出现异常",token,e);
            return null;
        }
        return JwtUtils.getUserKey(claims); //获取jwt中的key
    }

    // 解析token得到userId
    public Long getUserId (String token,String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token:{},出现异常",token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token:{},出现异常",token,e);
            return null;
        }
        return Long.valueOf(JwtUtils.getUserId(claims)); //获取jwt中的userId
    }

    // 从redis中获取用户信息
    public LoginUser getLoginUser(String token,String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return null;
        }
        // 从redis中把用户信息获取出来
        LoginUser loginUser = redisService.getCacheObject(CacheConstant.LOGIN_TOKEN_KEY + userKey, LoginUser.class);
        return loginUser;
    }

    // 从redis中删除用户信息
    public boolean deleteLoginUser(String token,String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(CacheConstant.LOGIN_TOKEN_KEY + userKey);
    }

    public void refreshLoginUser(String nickName, String headImage, String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }

    private String getTokenKey(String userKey) {
        return CacheConstant.LOGIN_TOKEN_KEY + userKey;
    }

}